package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.device.domain.PowerBank;
import com.share.device.mapper.PowerBankMapper;
import com.share.device.service.IPowerBankService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zxl
 * @date 2025年03月20日 21:23
 */
@Service
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank> implements IPowerBankService {
    /**
     * 充电宝列表查询
     * @param powerBank
     * @return
     */
    @Override
    public List<PowerBank> selectPowerBankList(PowerBank powerBank) {
        return baseMapper.selectPowerBankList(powerBank);
    }

    /**
     * 根据充电宝编号查询充电宝信息
     * @param powerBankNo
     * @return
     */
    @Override
    public PowerBank getByPowerBankNo(String powerBankNo) {
        return baseMapper.selectOne(new LambdaQueryWrapper<PowerBank>().
                eq(PowerBank::getPowerBankNo, powerBankNo));
    }

    /**
     * 新增充电宝信息
     * @param powerBank
     * @return
     */
    @Override
    public int savePowerBank(PowerBank powerBank) {
        long count = this.count(new LambdaQueryWrapper<PowerBank>().eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo()));
        if (count > 0) {
            throw new ServiceException("该充电宝编号已存在");
        }
        baseMapper.insert(powerBank);
        return 1;
    }

    /**
     * 更新充电宝信息
     * @param powerBank
     * @return
     */
    @Override
    public int updatePowerBank(PowerBank powerBank) {
        // 获取旧的数据
        PowerBank oldPowerBank = this.getById(powerBank.getId());

        if (null != oldPowerBank && !"0".equals(oldPowerBank.getStatus())) {
            throw new ServiceException("该充电宝已投放，无法修改");
        }
        if (null == oldPowerBank) {
            throw new ServiceException("该充电宝不存在");
        }
        // 判断充电宝编号是否改变
        if (!oldPowerBank.getPowerBankNo().equals(powerBank.getPowerBankNo())) {
            // 不一样，说明充电宝编号改变了,判断新的充电宝编号是否已经存在
            long count = this.count(new LambdaQueryWrapper<PowerBank>()
                    .eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo()));
            if (count > 0) {
                throw new ServiceException("该充电宝编号已存在");
            }
        }
        return baseMapper.updateById(powerBank);
    }
}
